package com.mice.springbootmodel.common.util;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Description LinkedHashMap版 LRU实现 当缓存满时 优先删除最不常用的数据
 * @Author mice
 * @Date 2020/3/11 16:11
 * @Version V1.0
 **/
public class LRUCache<K,V> extends LinkedHashMap<K,V> {

    private int MAX_SIZE;

    public LRUCache(int cacheSize){
        super((int) (Math.ceil(cacheSize/0.75)+1),0.75f,true);
        this.MAX_SIZE = cacheSize;
    }

    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
        return size()>MAX_SIZE;
    }

    public static void main(String[] args) {
        LRUCache lruCache = new LRUCache(8);
        lruCache.put(1,1);
        lruCache.put(2,2);
        lruCache.put(3,3);
        lruCache.put(4,4);
        lruCache.put(5,5);
        lruCache.put(6,6);
        System.out.println(lruCache);
        lruCache.get(6);
        lruCache.get(5);
        lruCache.get(4);
        System.out.println(lruCache);
        lruCache.put(7,7);
        lruCache.put(8,8);
        System.out.println(lruCache);
        lruCache.put(9,9);
        System.out.println(lruCache);
        //{1=1, 2=2, 3=3, 4=4, 5=5, 6=6}
        //{1=1, 2=2, 3=3, 6=6, 5=5, 4=4}
        //{1=1, 2=2, 3=3, 6=6, 5=5, 4=4, 7=7, 8=8}
        //{2=2, 3=3, 6=6, 5=5, 4=4, 7=7, 8=8, 9=9}
    }
}